package com.gxuwz.endrskyweather.apiclient;

import android.content.Context;
import android.util.Log;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.endrskyweather.R;
import com.gxuwz.endrskyweather.model.AlarmList;
import com.gxuwz.endrskyweather.model.Day;
import com.gxuwz.endrskyweather.model.ForecastDay;
import com.gxuwz.endrskyweather.model.Hour1dataItem;
import com.gxuwz.endrskyweather.model.LifeIndex;
import com.gxuwz.endrskyweather.model.Night;
import com.gxuwz.endrskyweather.model.Now;
import com.gxuwz.endrskyweather.model.Observe24h;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class BaiduBceApiClient24h implements IApiClient{

    private final String BASE_URL = "http://getweather.api.bdymkt.com/lundear/weather1d";

    private String API_ACCESS_KEY;
    private String API_SECRET_KEY;
    private Context context;
    private String jsonString;
    private ApiExplorerRequest request;
    private ApiExplorerClient client;
    private Gson gson;

    // 无缓存构造器，用于初始化API信息
    public BaiduBceApiClient24h(Context context) {
        Log.w("BaiduBceApiClient24h", "警告：使用了一次无缓存构造");
        this.context = context;
        initApiInfo();
        request = new ApiExplorerRequest(HttpMethodName.GET, BASE_URL);
        request.setCredentials(API_ACCESS_KEY, API_SECRET_KEY);
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
//        request.addQueryParameter("areaCn", "");
//        request.addQueryParameter("areaCode", "");
//        request.addQueryParameter("ip", "");
//        request.addQueryParameter("lat", "");
//        request.addQueryParameter("lng", "");
        request.addQueryParameter("need3hour", "1");
        request.addQueryParameter("needIndex", "1");
        request.addQueryParameter("needObserve", "1");
        request.addQueryParameter("needalarm", "1");
        request.addQueryParameter("need1hour", "1");
        jsonString = null;
        client = new ApiExplorerClient(new AppSigner());
        gson = new Gson();
    }

    // 有缓存构造器，用于直接传入缓存的json字符串
    public BaiduBceApiClient24h(String jsonString) {
        Log.w("BaiduBceApiClient24h", "警告：使用了一次有缓存构造");
        this.context = null;
        this.jsonString = jsonString;
        request = null;
        client = null;
        gson = new Gson();
    }

    // 内部获取原始JSON字符串
    private String jsonGet(String cityCode) {
        if (jsonString != null) return jsonString;
        try {
            request.addQueryParameter("areaCode", cityCode);
            ApiExplorerResponse response = client.sendRequest(request);
            jsonString = response.getResult();
            Log.w("BaiduBceApiClient24h", "警告：内部调用了一次API");
            return jsonString;
        } catch (Exception e) {
            Log.e("BaiduBceApiClient24h", "httpGet error: ", e);
            return null;
        }
    }

    // 内部方法，用于装入API密钥信息
    private void initApiInfo() {
        InputStream inputStream = context.getResources().openRawResource(R.raw.config);
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            Log.e("BaiduBceApiClient24h", "load properties error", e);
        }
        API_ACCESS_KEY = properties.getProperty("API_ACCESS_KEY");
        Log.d("ApiClient", "API_ACCESS_KEY:" + API_ACCESS_KEY);
        API_SECRET_KEY = properties.getProperty("API_SECRET_KEY");
        Log.d("ApiClient", "API_SECRET_KEY:" + API_SECRET_KEY);
    }

    @Override
    // 外部获取 json 字符串作为缓存
    public String httpGetJsonString(String cityCode) throws IOException {
        request.addQueryParameter("areaCode", cityCode);
        ApiExplorerResponse response = client.sendRequest(request);
        jsonString = response.getResult();
        Log.d("BaiduBceApiClient24h", "获取到的JSON字符串:" + jsonString);
        Log.w("BaiduBceApiClient24h", "警告：外部调用了一次API");
        return jsonString;
    }

    @Override
    public LifeIndex getLifeIndex(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("lifeIndex");
        return gson.fromJson(data.toString(), LifeIndex.class);
    }

    @Override
    public Now getNowWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        Log.d("ApiClient", "获取到的城市:" + new JSONObject(json).getJSONObject("data").getJSONObject("cityInfo").getString("areaCn"));
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("now");
        return gson.fromJson(data.toString(), Now.class);
    }

    @Override
    public Day getDayWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("day");
        return gson.fromJson(data.toString(), Day.class);
    }

    @Override
    public Night getNightWeather(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("night");
        return gson.fromJson(data.toString(), Night.class);
    }

    @Override
    public AlarmList getAlarmList(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String url = BASE_URL;
        String json = jsonGet(url);
        JSONArray array = new JSONObject(json).getJSONObject("data").getJSONArray("alarmList");
        // 读取 array 的第一个元素
        JSONObject data = array.getJSONObject(0);
        return gson.fromJson(data.toString(), AlarmList.class);
    }

    @Override
    public List<Hour1dataItem> getHour1Forecast(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        Log.d("ApiClient", "获取到的每日预报的城市:" + new JSONObject(json).getJSONObject("data").getJSONObject("cityInfo").getString("areaCn"));
        JSONArray array = new JSONObject(json).getJSONObject("data").getJSONArray("hour1data");
        return gson.fromJson(array.toString(), new TypeToken<List<Hour1dataItem>>(){}.getType());
    }

    @Override
    public List<String> getHour3Forecast(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        JSONArray array = new JSONObject(json).getJSONObject("data").getJSONArray("hour3data");
        return gson.fromJson(array.toString(), new TypeToken<List<String>>(){}.getType());
    }

    @Override
    public Map<String, ForecastDay> get7DayForecast(String cityCode) throws IOException, JSONException {
        return null;
    }

    @Override
    public Map<String, ForecastDay> get15DayForecast(String cityCode) throws IOException, JSONException {
        return null;
    }

    @Override
    public Observe24h getObserve24h(String cityCode) throws IOException, JSONException {
        Log.d("ApiClient", "获取到的CityCode:" + cityCode);
        String json = jsonGet(cityCode);
        JSONObject data = new JSONObject(json).getJSONObject("data").getJSONObject("observe24h");
        return gson.fromJson(data.toString(), Observe24h.class);
    }

}
